package www.wen.com.common.lib.extension

import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import www.wen.com.common.lib.app.BaseApplication.Companion.CONTEXT
import java.lang.reflect.Type


/**
 * @author WEN
 * @Description:
 * @date 2021/1/29 13:44
 */

fun Any.getString(@StringRes id: Int): String {
    return CONTEXT.resources.getString(id)
}

fun Any.getDrawableAgency(@DrawableRes id: Int): Drawable? {
    return ContextCompat.getDrawable(CONTEXT, id)
}

fun Any.getColorAgency(@ColorRes id: Int): Int {
    return ContextCompat.getColor(CONTEXT, id)
}

inline fun <reified T> Any.typeFromJson(json: String): T {
    val type: Type = object : TypeToken<T>() {}.type
    return Gson().fromJson(json, type) as T
}

fun <T> Any.pareEntity(json: T): String {
    return GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(json)
}


/**
 * 倒计时
 */
fun Any.countDownCoroutines(
        total: Int,
        onTick: ((Int) -> Unit)? = null,
        onFinish: (() -> Unit)? = null,
        onCancel: (() -> Unit)? = null,
        scope: CoroutineScope = GlobalScope
): Job {
    return flow {
        for (i in total downTo 0) {
            emit(i)
            delay(1000)
        }
    }.flowOn(Dispatchers.Default)
            .onCompletion {
                onCancel?.invoke()
            }
            .onEach {
                if (it == 0) {
                    onFinish?.invoke()
                }
                onTick?.invoke(it)
            }
            .flowOn(Dispatchers.Main)
            .launchIn(scope)
}



